<!--suppress ALL -->
<template>
  <div v-loading="loading" class="createPost-container" style="padding-top: 40px">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" class="demo-ruleForm" style="padding-left:100px;padding-right:100px;">
      <h3>{{ $t('good.detail.form.title.basic_information') }}</h3>
      <el-form-item :label="$t('good.detail.form.type.label')" prop="type" style="width:700px;">
        <el-radio-group v-model="ruleForm.type">
          <el-radio-button label="news">新闻公告</el-radio-button>
          <el-radio-button label="notice">其他内容</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="标题" prop="title" style="width:600px;">
        <el-input v-model="ruleForm.title" maxlength="60" clearable />
      </el-form-item>
      <el-form-item :label="$t('good.detail.form.tinymce.details')" prop="content">
        <tinymce ref="editor" v-model="ruleForm.content" :disabled="disabled" :url="actionurl" :header="imgHeaders" />
      </el-form-item>
      <el-form-item class="float-button">
        <el-button :loading="formLoading" type="primary" @click="dialogStatus==='create'?create():edit()">{{ $t('common.submit') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { create, edit } from '@/api/news'
import { getToken } from '@/utils/auth'
import tinymce from '@/components/tinymce5'
import Sku from '@/components/skutwo'
import 'video.js/dist/video-js.css'
import { videoPlayer } from 'vue-video-player'
export default {
  name: 'NewsDetail',
  components: {
    tinymce,
    Sku,
    videoPlayer
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formLoading: false,
      dialogFormVisible: false,
      freight: [],
      disabled: false,
      sku: [],
      goods_brand: [],
      attributeMarket: [],
      dialogImageUrl: '',
      actionurl: process.env.BASE_API + 'uploadPictures',
      imgHeaders: {
        Authorization: 'Bearer ' + getToken('access_token')
      },
      good_attribute: [],
      goods_type: [],
      imgMasterData: {
        type: 1,
        size: 1024 * 1024 * 2,
        specification: [80, 150, 200, 250, 300, 350]
      },
      imgData: {
        type: 1,
        size: 1024 * 1024 * 2
      },
      dialogVisible: false,
      loading: false,
      id: '',
      ruleForm: {
        type: 'news',
        title: '',
        content: ''
      },
      imgProgress: false,
      dialogStatus: 'create',
      imgProgressPercent: 0,
      rules: {
        title: [
          { required: true, message: this.$t('hint.error.please_enter', { attribute: '标题' }), trigger: 'blur' }
        ],
        content: [
          { required: true, message: this.$t('hint.error.please_enter', { attribute: this.$t('good.detail.details') }), trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    playerOptions() {
      return {
        playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: getToken('language') ? getToken('language') === 'zh' ? 'zh-CN' : getToken('language') : 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: '',
          src: '' // url地址
        }],
        poster: '', // 你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: this.$t('good.detail.player_options_not_supported_message'), // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true // 全屏按钮
        }
      }
    },
    freightLang() {
      const lang = this.ruleForm.lang ? this.ruleForm.lang : this.$store.state.app.language
      return this.freight.filter((element) => { return element.lang === lang })
    },
    goodsTypeLang() {
      const lang = this.ruleForm.lang ? this.ruleForm.lang : this.$store.state.app.language
      return this.goods_type.filter((element) => { return element.lang === lang })
    },
    goodsBrandLang() {
      const lang = this.ruleForm.lang ? this.ruleForm.lang : this.$store.state.app.language
      return this.goods_brand.filter((element) => { return element.lang === lang })
    }
  },
  created() {
    this.id = this.$route.query.id
    if (this.id) {
      this.dialogStatus = 'update'
    } else {
      this.dialogStatus = 'create'
    }
    if (this.$route.params.lang) {
      const params = this.$route.params
      this.ruleForm = { ...params, ...this.ruleForm }
    }
    this.getList()
  },
  methods: {
    validateFields(rule, value, callback) {
      if (this.ruleForm.price || this.getSkuData().length) {
        callback()
      } else {
        callback(new Error(this.$t('hint.error.not_null', { attribute: this.$t('good.detail.fixed_price') })))
      }
    },
    validateInventoryFields(rule, value, callback) {
      if (this.ruleForm.inventory || this.getSkuData().length) {
        callback()
      } else {
        callback(new Error(this.$t('hint.error.not_null', { attribute: this.$t('good.detail.total_quantity') })))
      }
    },
    getList() {
      this.loading = false
      if (sessionStorage.getItem('formInfo')) {
        this.ruleForm = JSON.parse(sessionStorage.getItem('formInfo'))
        this.ruleForm = { ...this.ruleForm, type: this.ruleForm.type === '新闻' ? 'news' : 'notice' }
      }
    },
    create() { // 添加
      this.formLoading = true
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          create(this.ruleForm).then(() => {
            this.$notify({
              title: this.$t('common.succeed'),
              message: this.$t('hint.succeed.win', { attribute: this.$t('common.add') }),
              type: 'success',
              duration: 2000
            })
            this.formLoading = false
            setTimeout(this.$router.back(-1), 2000)
          }).catch(() => {
            this.formLoading = false
          })
        } else {
          this.formLoading = false
        }
      })
    },
    edit() { // 更新
      this.formLoading = true
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (!this.ruleForm.video) {
            this.ruleForm.videoArr = null
            this.ruleForm.video = null
          }
          edit(this.ruleForm).then(() => {
            this.$notify({
              title: this.$t('common.succeed'),
              message: this.$t('hint.succeed.win', { attribute: this.$t('common.update') }),
              type: 'success',
              duration: 2000
            })
            this.formLoading = false
            setTimeout(this.$router.back(-1), 2000)
            // setTimeout(this.$router.push({ path: '/commodityManagement/good/goodList?page=' + this.$route.query.page + '&activeIndex=' + this.$route.query.activeIndex }), 2000)
          }).catch(() => {
            this.formLoading = false
          })
        } else {
          this.formLoading = false
        }
      })
    },
    // 上传成功
    handleAvatarSuccess(res, file) {
      this.ruleForm.img = file.response
      this.imgProgress = false
      this.imgProgressPercent = 0
    },
    // 上传时
    handleProgress(file, fileList) {
      this.imgProgressPercent = file.percent
    },
    // 图片格式大小验证
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (
        [
          'image/jpeg',
          'image/gif',
          'image/png'
        ].indexOf(file.type) === -1) {
        this.$message.error(this.$t('hint.upload.img.rmvb'))
        return false
      }
      if (!isLt2M) {
        this.$message.error(this.$t('hint.upload.img.can_not_surpass', { size: '2MB' }))
      }
      this.imgProgress = true
      return isLt2M
    },
    // 图片列表图片格式大小验证
    beforeAvatarUploadList(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (
        [
          'image/jpeg',
          'image/gif',
          'image/png'
        ].indexOf(file.type) === -1) {
        this.$message.error(this.$t('hint.upload.img.rmvb'))
        return false
      }
      if (!isLt2M) {
        this.$message.error(this.$t('hint.upload.img.can_not_surpass', { size: '2MB' }))
      }
      return isLt2M
    },
    // 图片列表上传成功
    handleAvatarSuccessList(res, file, fileList) {
      this.ruleForm.imgList = fileList
      this.imgProgress = false
      this.imgProgressPercent = 0
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.ruleForm.imgList = fileList
    },
    // 显示规格
    // 设置视频地址
    setVideo(event) {
      this.playerOptions['sources'][0]['src'] = this.ruleForm.video
    },
    // 设置视频封面
    setPoster(event) {
      this.playerOptions['poster'] = this.ruleForm.poster
    },
    // 重新加载无法输入或选择
    change(e) {
      this.$forceUpdate()
    },
    // 设置类型
    setType(e) {
      this.$refs.SkuDemo._setType(e)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.createPost-container {
  padding-bottom: 60px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 188px;
  height: 188px;
  line-height: 188px;
  text-align: center;
}
.progress-img {
  padding: 30px;
}
.avatar {
  width: 188px;
  height: 188px;
  display: block;
}
.avatar-uploaders .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploaders .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icons {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.progress-imgs {
  padding: 5px;
}
.float-button {
  position: fixed;
  bottom: 0px;
  right: 0;
  padding-right: 10%;
  padding-top: 10px;
  padding-bottom: 10px;
  width: 100%;
  margin-bottom: 0;
  background-color: #ffffff;
  text-align: right;
  z-index: 999;
  line-height: 50px;
  border-top: 1px solid #e5e5e5;
}
</style>
